import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import UserView from '@/views/main/UserView.vue'
import BookView from '@/views/main/BookView.vue'
import IndexView from '@/views/main/IndexView.vue'

import { useUserStore } from '@/stores/userStores.js'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      redirect: '/index',
      children: [
        {
          path: '/user',
          name: 'user',
          component: UserView,
          meta: {
            role:['admin','teacher']

          },
          children: [
            {
              path: '/user/detail',
              name: 'detail',
              component: () => import('@/views/main/user/UserDetailsView.vue'),
            },
          ]
        },{
          path: '/index',
          name: 'index',
          component: IndexView,
          meta: {
            role:['admin','student','teacher']

          },
        },{
          path: '/book',
          name: 'book',
          component: BookView,
          meta: {
            role:['admin','teacher']

          },
        },{
          
          path: '/borrow',
          name: 'borrow',
          component: () => import('@/views/main/BorrowView.vue'),
          meta: {
            role:['admin','student']

          },
        },
      ]
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('@/views/AboutView.vue'),
      meta: {
        role:['admin','student','teacher']

      },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: {
        role:['admin','student','teacher']

      },
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/404.vue'),
      meta: {
        role:['admin','student','teacher']

      },
    },
  ],
})


router.beforeEach((to, from, next) => {

  const userStore = useUserStore()
  const userInfo = userStore.getUserInfo()

  const requestRoles = to.meta.role;




    if (!userInfo) {
      if (to.name === 'login') {
        next();
      } else {
        next({ name: 'login' });
      }
      return;
    }

    console.log(requestRoles);
    console.log(userInfo.role);
    


    // if (requestRoles && !requestRoles.includes(userInfo.role)) {
    //   next({ name: '404'})
      
    // }



    next()
  




})



export default router